// 用户路由单元
var express = require('express');
var router = express.Router();
// 导入连接池对象
const sql = require('../db/index')
// 引入jwt
const jwt = require('jsonwebtoken')

// 引入响应体
const Response = require('../utils/response')

/**
 * @swagger
 * /user/login:
 *   post:
 *     summary: 用户登录
 *     tags: [用户]
 *     description: 根据用户名和密码进行用户登录，返回 token。
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
*             type: object
 *             required:
 *               - username
 *               - password
 *             properties:
 *               username:
 *                 type: string
 *                 example: "admin1"
 *               password:
 *                 type: string
 *                 example: "123456"
 *     responses:
 *       200:
 *         description: 登录成功，返回 token
 *       401:
 *         description: 密码错误
 *       404:
 *         description: 用户不存在
 */
// 登录接口
router.post('/login', async (req, res) => {
  // console.log(req);
  const { username, password } = req.body
  const [response] = await sql.execute('select * from base_user where username =?', [username])
  console.log(response);
  // 用户不存在
  if (response.length == 0) {
    res.send(new Response(404, '用户不存在', null))
  }
  // 匹配密码
  if (response[0].password == password.toString()) {
    res.send(new Response(200, '登录成功', { token: jwt.sign({ username }, 'Bear', { expiresIn: '72h' }) }))
  }
  else {
    res.send(new Response(401, '密码错误', null))
  }
})

/**
 * @swagger
 * /user/info:
 *   get:
 *     summary: 获取用户个人信息
 *     tags: [用户]
 *     description: 该接口用于获取当前用户的个人信息。必须通过授权的 token 进行验证。
 *     parameters:
 *       - name: Authorization
 *         in: header
 *         required: true
 *         description: 用户的 JWT token，用于身份验证。
 *         schema:
 *           type: string
 *           example: "your_jwt_token"
 *     responses:
 *       200:
 *         description: 获取个人信息成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   example: 200
 *                 message:
 *                   type: string
 *                   example: "获取个人信息成功"
 *                 data:
 *                   type: object
 *                   description: 用户个人信息对象
 *                   properties:
 *                     username:
 *                       type: string
 *                       example: "exampleUser"
 *                     email:
 *                       type: string
 *                       example: "user@example.com"
 *       401:
 *         description: 未授权
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   example: 401
 *                 message:
 *                   type: string
 *                   example: "未授权"
 *       403:
 *         description: 无效 token
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   example: 403
 *                 message:
 *                   type: string
 *                   example: "无效token"
 *       404:
 *         description: 用户不存在
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   example: 404
 *                 message:
 *                   type: string
 *                   example: "用户不存在"
 */
// 通过token获取个人信息
router.get('/info', (req, res) => {
  const token = req.headers['authorization'];
  if (!token) {
    res.send(new Response(401, '未授权', null))

  } else {
    jwt.verify(token, 'Bear', async (err, decoded) => {
      if (err) {
        res.send(new Response(403, '无效token', null))
      } else {
        const { username } = decoded;
        try {
          const [userInfo] = await sql.query('SELECT * FROM base_user WHERE username = ?', [username]);
          if (userInfo.length === 0) {
            res.send(new Response(404, '用户不存在', null))
          } else {
            const userId = userInfo[0].id;
            const [roles] = await sql.query('SELECT role_name, id FROM base_role WHERE id IN (SELECT role_id FROM base_user_role WHERE user_id = ?)', [userId]);
            // 将 roles 数组添加到 userInfo 对象中
            userInfo[0].roles = roles.map(role => ({ id: role.id, name: role.role_name }));
            console.log(userInfo[0]);
            res.send(new Response(200, '获取成功', userInfo[0]))
          }
        } catch (error) {
          console.error(error);
          res.send({ status: 500, message: '服务器错误', data: null });
          res.send(new Response(500, '服务器错误', null))
        }
      }
    });
  }
});

/**
 * @swagger
 * /user/logout:
 *   post:
 *     summary: 用户退出登录
 *     tags: [用户]
 *     description: 该接口用于用户退出登录，返回退出成功的消息。
 *     responses:
 *       200:
 *         description: 退出成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   example: 200
 *                 message:
 *                   type: string
 *                   example: 退出成功
 *                 data:
 *                   type: object
 *                   nullable: true
 */
// 退出
router.post('/logout', async (req, res) => {
  res.send(new Response(200, '退出成功', null))
})


/**
 * @swagger
 * /user/register:
 *   post:
 *     summary: 用户注册
 *     tags: [用户]
 *     description: 该接口用于用户注册。用户需要提供必要的注册信息。
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               username:
 *                 type: string
 *                 example: "larry"
 *               password:
 *                 type: string
 *                 example: "123321"
 *               telephone:
 *                 type: string
 *                 example: "1234567890"
 *               userFace:
 *                 type: string
 *                 example: "Null"
 *               brith:
 *                 type: string
 *                 example: "Null"
 *               gender:
 *                 type: string
 *                 example: "male"
 *     responses:
 *       201:
 *         description: 注册成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   example: 201
 *                 message:
 *                   type: string
 *                   example: "注册成功"
 *                 data:
 *                   type: object
 *                   nullable: true
 *       409:
 *         description: 用户已存在
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   example: 409
 *                 message:
 *                   type: string
 *                   example: "该用户已经存在"
 *                 data:
 *                   type: object
 *                   nullable: true
 */
// 注册接口
router.post('/register', async (req, res) => {
  // 获取参数 前端穿过的用户信息
  const { username, password, telephone, userFace = 'null', birth = 'null', gender } = req.body
  const [response] = await sql.query('select * from order_user where username =?', [username])
  if (response.length) {
    res.send(new Response(409, '该用户已经存在', null))
  } else {
    await sql.query('insert into order_user ( username, password, telephone, userFace, birth, gender) values(?,?,?,?,?,?)', [username, password, telephone, userFace, birth, gender])
    res.send(new Response(200, '注册成功', null))
  }

})



// 保存或更新用户信息
router.post('/saveOrUpdate', async (req, res) => {
  const { id, username, password, telephone, birth, gender, userFace, realname, roles, status } = req.body;

  // 构建更新的字段和值
  const updates = {};
  if (username !== undefined) updates.username = username;
  if (password !== undefined) updates.password = password;
  if (telephone !== undefined) updates.telephone = telephone;
  if (birth !== undefined) updates.birth = birth;
  if (gender !== undefined) updates.gender = gender;
  if (userFace !== undefined) updates.userFace = userFace;
  if (realname !== undefined) updates.realname = realname;
  if (roles !== undefined) updates.roles = roles;
  if (status !== undefined) updates.status = status;
  try {
    let result;
    if (id) {
      // 如果有id，尝试更新记录
      result = await sql.query('UPDATE base_user SET ? WHERE id = ?', [updates, id]);
      res.json(new Response(200, '更新成功', result));
    } else {
      // 如果没有id，检查用户名是否已存在
      const [checkUser] = await sql.query('SELECT * FROM base_user WHERE username = ?', [username]);
      if (checkUser.length !== 0) {
        // 如果用户名已存在，返回错误响应
        return res.json(new Response(400, '用户名已存在,请重新创建', null));
      }
      // 用户名不存在，创建新记录
      result = await sql.query('INSERT INTO base_user SET ?', updates);
      res.json(new Response(201, '创建成功', result));

    }
  } catch (error) {
    // 使用封装的Response对象返回错误结果
    return res.json(new Response(500, '服务器错误', error));
  }
});



router.post('/setRoles', async (req, res) => {
  const { userId, roleId } = req.body;

  // 检查请求体，确保 userId 存在
  if (!userId) {
    return res.status(400).json({ message: 'userId is required' });
  }
  try {
    // 插入或更新用户角色的 SQL 查询语句
    // 如果 user_id 已存在，则更新 role_id
    const query = `
          INSERT INTO base_user_role (user_id, role_id)
          VALUES (?,?)
          ON DUPLICATE KEY UPDATE role_id = VALUES(role_id);`;
    // 如果 roleId 为空，则设置为 NULL
    const values = [userId, roleId || null];
    // 执行数据库查询
    await sql.query(query, values);
    // 如果成功，返回 200 状态码和成功消息
    return res.status(200).json({ message: '设置成功' });
  } catch (error) {
    // 如果出现错误，打印错误并返回 500 状态码和错误消息
    console.error(error);
    return res.status(500).json({ message: '服务器错误' });
  }
});


// 统计用户数量的接口
router.get('/getRolesCount', async (req, res) => {
  const query = `
          SELECT r.role_name, COUNT(ur.user_id) AS user_count
          FROM base_role r
          LEFT JOIN base_user_role ur ON r.id = ur.role_id
          GROUP BY r.role_name
      `;
  try {
    const results = await sql.query(query); // 使用 async/await 处理异步操作
    // console.log(results[0]);
    let counts = {}
    counts.count = results[0]
    console.log(counts);
    res.send(new Response(200, '获取成功', counts)); // 成功时返回结果
  } catch (err) {
    res.send(new Response(500, '服务器错误', null)) // 返回500错误
  }
});

// 获取教师用户
router.get('/teachers', async (req, res) => {
  try {
    const query = `
      SELECT u.*
      FROM base_user u
      JOIN base_user_role ur ON u.id = ur.user_id
      JOIN base_role r ON ur.role_id = r.id AND r.role_name = '导师'
    `;
    const [results] = await sql.query(query);
    console.log(results);

    res.send(new Response(200, '获取导师数据成功', {
      list: results
    }
    ))

  } catch (error) {
    console.error('获取导师数据失败', error);
    res.send(new Response(500, '获取导师数据失败', error))

  }
});

router.get('/pageQueryFind', async (req, res) => {
  const { realname, page, pageSize } = req.query;
  const offset = (page - 1) * pageSize;

  // 初始化一个数组来存储构建 SQL 条件的片段
  const condition = [];
  // 初始化一个数组来存储与条件片段相对应的值
  const values = [];

  // 如果请求中包含 realname 参数，则添加一个条件片段和对应的值
  if (realname) {
    condition.push('base_user.realname LIKE ?');
    values.push(`%${realname}%`);
  }

  // 根据条件片段数组的长度，构建完整的 SQL 条件字符串
  let sqlStr = condition.length ? `WHERE ${condition.join(' AND ')}` : '';
  // 打印构建的 SQL 条件字符串到控制台
  console.log(sqlStr);

  try {
    // 使用内连接（INNER JOIN）来联合 base_user、base_role 和 base_user_role 表，并根据构建的条件进行筛选
    // LIMIT 和 OFFSET 用于实现分页功能
    const [users] = await sql.query(
      `SELECT base_user.*, base_role.role_name FROM base_user 
      INNER JOIN base_user_role ON base_user.id = base_user_role.user_id 
      INNER JOIN base_role ON base_user_role.role_id = base_role.id 
        ${sqlStr} LIMIT ? OFFSET ?`,
      [...values, parseInt(pageSize, 10), parseInt((page - 1) * pageSize, 10)]
    );

    // 为了获取符合条件的用户总数，执行另一个 SQL 查询
    // 这个查询和获取用户列表的查询类似，但不包括 LIMIT 和 OFFSET
    const [totalCount] = await sql.query(
      `SELECT count(*) as count FROM base_user INNER JOIN base_user_role ON base_user.id = base_user_role.user_id INNER JOIN base_role ON base_user_role.role_id = base_role.id ${sqlStr}`,
      values
    );
    // 从查询结果中获取总数
    const total = totalCount[0].count;

    // 如果查询成功，发送一个包含用户列表、总数、当前页和每页大小的响应
    res.send({
      status: 200,
      message: '获取成功',
      data: {
        list: users, // 将查询到的用户列表赋值给 list 属性
        total: total,
        page: parseInt(page),
        pageSize: parseInt(pageSize)
      }
    });
  } catch (error) {
    // 如果在查询过程中发生错误，打印错误信息到控制台
    console.error('Error fetching users:', error);
    // 发送一个包含错误信息的响应
    res.status(500).send({
      status: 500,
      message: '用户查询错误',
      data: null
    });
  }
});



router.get('/getAllRoles', async (req, res) => {
  const query = `SELECT id, role_name FROM base_role WHERE role_name IN ('导师', '管理员', '学生')`;
  const [roles] = await sql.query(query);
  const formattedRoles = roles.map(role => ({ id: role.id, role_name: role.role_name }));
  res.send(new Response(200, '获取成功', formattedRoles));
});


router.get('/deleteById', async (req, res) => {
  const { id } = req.query;
  if (!id) {
    return res.send(new Response(400, '用户 ID 未提供', null));
  }
  const deleteUserQuery = `DELETE FROM base_user WHERE id =?`;
  await sql.query(deleteUserQuery, [id]);
  res.send(new Response(200, '用户删除成功', null));

});


router.post('/addUserWithRole', async (req, res) => {
  const { username, password, role_id } = req.body;
  if (!username || !password || !role_id) {
    return res.send(new Response(400, '缺少必要字段', null));
  }
  // 插入用户到 base_user 表
  const insertUserQuery = `INSERT INTO base_user (username, password) VALUES (?,?)`;
  const [userResult] = await sql.query(insertUserQuery, [username, password]);
  const newUserId = userResult.insertId;

  // 将用户与角色关联插入到 base_user_role 表
  const insertUserRoleQuery = `INSERT INTO base_user_role (user_id, role_id) VALUES (?,?)`;
  await sql.query(insertUserRoleQuery, [newUserId, role_id]);

  return res.send(new Response(200, '用户添加成功并设置角色', null));
});


router.post('/updateUserRole', async (req, res) => {
  const { user_id, role_id } = req.body;
  if (!user_id || !role_id) {
    return res.send(new Response(400, '用户 ID 和角色 ID 未提供', null));
  }
  const updateQuery = `UPDATE base_user_role SET role_id =? WHERE user_id =?`;
  await sql.query(updateQuery, [role_id, user_id]);
  return res.send(new Response(200, '用户角色更新成功', null));
});


router.get('/getUserById', async (req, res) => {
  const { id } = req.query;
  if (!id) {
    return res.send(new Response(400, '用户 ID 未提供', null));
  }
  const getUserQuery = `
      SELECT u.*, r.role_name
      FROM base_user u
      JOIN base_user_role ur ON u.id = ur.user_id
      JOIN base_role r ON ur.role_id = r.id
      WHERE u.id =?;
  `;
  const [userResult] = await sql.query(getUserQuery, [id]);
  if (userResult.length === 0) {
    return res.send(new Response(404, '用户不存在', null));
  }
  const user = userResult[0];
  return res.send(new Response(200, '用户信息获取成功', user));
});
module.exports = router;